import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 用户登录状态
  const isLoggedIn = ref(false)
  const userMode = ref('normal') // 'normal' | 'gray'
  
  // 用户信息
  const userInfo = reactive({
    id: null,
    username: '',
    email: '',
    role: '',
    joinDate: '',
    activeProjects: 0,
    monthlyExecutions: 0,
    passRate: '',
    mode: 'normal'
  })

  // 默认未登录用户显示信息
  const defaultUserInfo = {
    username: '游客',
    role: '未登录用户',
    email: '',
    joinDate: '',
    activeProjects: 0,
    monthlyExecutions: 0,
    passRate: '0%'
  }

  // 登录方法
  const login = (userData) => {
    isLoggedIn.value = true
    userMode.value = userData.mode || 'normal'
    
    Object.assign(userInfo, {
      id: userData.id || '001',
      username: userData.username || '冰酱',
      email: userData.email || 'test@company.com',
      role: userData.role || '高级测试开发工程师',
      joinDate: userData.joinDate || '2023-01-15',
      activeProjects: userData.activeProjects || 12,
      monthlyExecutions: userData.monthlyExecutions || 156,
      passRate: userData.passRate || '89%',
      mode: userData.mode || 'normal'
    })
    
    // 保存到localStorage
    localStorage.setItem('userToken', 'mock-token-' + Date.now())
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    localStorage.setItem('userMode', userMode.value)
  }

  // 登出方法
  const logout = () => {
    isLoggedIn.value = false
    userMode.value = 'normal'
    Object.assign(userInfo, defaultUserInfo)
    
    // 清除localStorage
    localStorage.removeItem('userToken')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userMode')
  }

  // 检查登录状态（用于页面刷新后恢复状态）
  const checkLoginStatus = () => {
    const token = localStorage.getItem('userToken')
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedUserMode = localStorage.getItem('userMode')
    
    if (token && savedUserInfo) {
      try {
        const userData = JSON.parse(savedUserInfo)
        isLoggedIn.value = true
        userMode.value = savedUserMode || 'normal'
        Object.assign(userInfo, userData)
      } catch (error) {
        console.error('Failed to parse user info:', error)
        logout()
      }
    }
  }

  // 初始化时检查登录状态
  checkLoginStatus()

  return {
    isLoggedIn,
    userMode,
    userInfo,
    defaultUserInfo,
    login,
    logout,
    checkLoginStatus
  }
})